<?php
require_once 'Zend/Db.php';
require_once 'Zend/Config/Ini.php';
require_once 'tools/des.php';
//require_once 'FtpHelper.php';
/**
 * 主控受控使用的脚本
 * @author Administrator
 *
 */
class miniFun{
	private $minicmdpath="";
	private $minicmdwebpath="";
	private $u="bjswaxkjfzyxgs@";
	function miniFun(){
    	$this->minicmdpath = "/data/web/library/Common/Command/";//命令路径
    	$this->minicmdwebpath = "/data/web/public/minicmd/";//命令中使用的web路径
		if (!file_exists($this->minicmdwebpath)){
    			system("mkdir -p ".$this->minicmdwebpath);}//创建路径
	}
    //private $basePath="/data/webroot/minicms/web/public/images/";
	private function db()
    {   
        $params = array ('host' => '127.0.0.1',
                 'port' => '3306',
                 'username' => 'root',
                 'password' => 'soooner.com',
                 'charset' => 'UTF8',
                 'dbname'   => 'minicms');
        $db = Zend_Db::factory('PDO_MYSQL', $params);
        return $db;
    }
    
    private function getConfig()//获取配置信息
    {
    	$db = $this->db();
    	$configrows = $db->fetchAll("select configname, configvalue from config");//获取配置信息
        $configs = array();
    	if (!empty($configrows)){
	       foreach ($configrows as $item){
	          $configs[$item['configname']] = $item['configvalue'];}
    	}//配置信息获取完成
    	return $configs;
    }
    /*
     * 修改slave的心跳时间
     * */
    private function touchSlave($id){
    	$db = $this->db();
    	return $db->query("update slaves set uptime = '".time()."' where id=$id");
    }
    
    private function getSlaves()//获取受控IP
    {
    	$db = $this->db();
    	$slavesrows = $db->fetchAll("select id,ip from slaves");
    	return $slavesrows;
    }
    
    private function getVips()//获取本机的vip
    {
    	$configs = $this->getConfig();
    	$db = $this->db();
    	$viprows = $db->fetchAll("select distinct(lvsvip.virtualipaddress) as vip from lvsservers left join lvsvip on lvsservers.vip = lvsvip.id where lvsservers.serverlip = :myip",array("myip"=>$configs["myip"]));
    	return $viprows;
    }
    /*生成mysql的配置文件 
     * */
    private function cnf($id,$ip,$ismaster=true){
    	$content = "";
    	if($ismaster){
    		$content = '[mysqld]
datadir=/data/mysql
socket=/tmp/mysql.sock
user=mysql
symbolic-links=0
log-bin=/data/mysql/updatelog
server-id = '.$id.'
binlog-do-db=minicms
binlog-ignore-db=mysql
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/tmp/mysqld.pid';
    	}else{
    		$content = '[mysqld]
datadir=/data/mysql
socket=/tmp/mysql.sock
user=mysql
symbolic-links=0
server-id = '.$id.'
master-host = '.$ip.'
master-user = root
master-password = soooner.com
master-port = 3306
replicate-ignore-db=mysql
replicate-do-table=minicms.category
replicate-do-table=minicms.epg
replicate-do-table=minicms.live
replicate-do-table=minicms.vod
replicate-do-table=minicms.vodlist
replicate-do-table=minicms.slaves
replicate-do-table=minicms.mediatype
replicate-do-table=minicms.lvsdatacenter
replicate-do-table=minicms.lvsmonitors
replicate-do-table=minicms.lvsservers 
replicate-do-table=minicms.lvsvip
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/tmp/mysqld.pid';
    	}
    	return $content;
    }
    
    /**
     * 时移路径初始化
     * */
    private function mktsdir(){
    	$disks=array();//硬盘数组
    	for($i=1;$i<8;$i++){
    		$diskpath="/mnt/disk-$i";//硬盘路径
    		if(file_exists($diskpath)){
    			$disks[]=$diskpath;
    			//创建ftp使用的目录
    			system("mkdir -p /data/media/$i");//创建路径
    			system("mkdir -p /mnt/disk-$i/ftp");//创建路径
    			system("chown -R minicms:ftp /mnt/disk-$i/ftp");//设置权限
    			system("umount /mnt/disk-$i/media/$i");
    			system("mount --bind -o rw /data/media/$i /mnt/disk-$i/ftp");//绑定目录
    		}
    	}
    	$db = $this->db();
    	$tsrows = $db->fetchAll("select vid from live where ists=1");
    	$disknum = count($disks);
    	if(!file_exists("/data/timeshift")){
    		system("mkdir -p /data/timeshift");
    	}
    	foreach($tsrows as $row){
    		$vid = $row["vid"];
    		if(!file_exists("/data/timeshift/$vid")){
    			$diskindex = $vid % $disknum;
    			system("mkdir -p ".$disks[$diskindex]."/timeshift/".$vid);
    			if($diskindex!=0){//硬盘编号
    				system("ln -sf ".$disks[$diskindex]."/timeshift/".$vid." /data/timeshift/$vid");
    			}
    		}
    		$vidlow = $row["vid"]."low";
    		if(!file_exists("/data/timeshift/$vidlow")){
    			$diskindex = $vid % $disknum;
    			system("mkdir -p ".$disks[$diskindex]."/timeshift/".$vidlow);
    			if($diskindex!=0){//硬盘编号
    				system("ln -sf ".$disks[$diskindex]."/timeshift/".$vidlow." /data/timeshift/$vidlow");
    			}
    		}
    	}
    }
    
    /*设备切换为主控模式 
     * */
    function cmd35()
    {
    	try{
	    	system("rm -f ".$this->minicmdwebpath."*");//删除该目录下的文件
	    	system("cd /root/.ssh\n rm -f id_rsa*\n ssh-keygen -t rsa -f /root/.ssh/id_rsa -P '' >>nohup \n cat id_rsa.pub > authorized_keys\n cat id_rsa.pub > ".$this->minicmdwebpath."rsa_pub.html\n echo \"StrictHostKeyChecking no\" >>/etc/ssh/ssh_config");//生成rsapub
	    	$this->backup("/etc/ssh/", "ssh_config");
	    	des::DesEf($this->minicmdwebpath."rsa_pub.html");//加密文件
	    	$configs = $this->getConfig();
	    	$state = $configs["state"];//状态
	    	$controller = $configs["controller"];//主控IP
	    	$slaves = $this->getSlaves();//受控IP
	    	$cnfcontent = $this->cnf("0", "");
	    	file_put_contents($this->minicmdpath."my.cnf.master", $cnfcontent);//本机使用，不加密
	    	system("touch ".$this->minicmdwebpath."ok.htm");
	    	system("cp ".$this->minicmdpath."my.cnf.master /etc/my.cnf -f");
	    	system("cp ".$this->minicmdpath."my.cnf.master ".$this->minicmdpath."my.cnf -f");//备份
	    	$this->backup("/etc/", "my.cnf");
	    	system("wget http://".$controller."/notify/touch/signal/36 -O /dev/null");//通知主控端重启mysql
	    	system("touch ".$this->minicmdwebpath."mysqlok.htm");
	    	foreach($slaves as $slave){
	    		$cnfcontent = $this->cnf($slave["id"], $controller,false);
	    		file_put_contents($this->minicmdpath."my.cnf.slave".$slave["id"], $cnfcontent);//生成slave配置文件
	    		system("wget http://".$slave["ip"]."/notify/touch/signal/37 -O /dev/null");//通知受控端
	     	}
    	}catch(Exception $e){
    	}  
    }
   	/*
   	 * 重启mysql
   	 * */
     function cmd36(){
     		$db = $this->db();
     		$configs = $this->getConfig();
	    	$state = $configs["state"];//状态
	    	$controller = $configs["controller"];
	    	if($state=="master"){
	    		system("service mysqld reload");
	    		system("service mysqld restart");
	    		$slaverows = $db->fetchAll("select id, ip, sip, des, uptime, liveport, vodport, tsport from slaves;");
	    		$slavesql="truncate table slaves;insert into slaves(id, ip, sip, des, uptime, liveport, vodport, tsport) values ";
	    		for($i=0;$i<count($slaverows);$i++){
	    			$slaverow = $slaverows[$i];
	    			if($i==0)
	    				$slavesql.="('".$slaverow["id"]."','".$slaverow["ip"]."','".$slaverow["sip"]."','".$slaverow["des"]."','".$slaverow["uptime"]."','".$slaverow["liveport"]."','".$slaverow["vodport"]."','".$slaverow["tsport"]."')";
	    			else
	    				$slavesql.=",('".$slaverow["id"]."','".$slaverow["ip"]."','".$slaverow["sip"]."','".$slaverow["des"]."','".$slaverow["uptime"]."','".$slaverow["liveport"]."','".$slaverow["vodport"]."','".$slaverow["tsport"]."')";
	    		}
	    		$rows = $db->fetchAll("show master status;");
	    		//$slaveinfo = "CHANGE MASTER TO MASTER_LOG_FILE='".$rows[0]["File"]."',MASTER_LOG_POS=".$rows[0]["Position"].";";
	    		$slaveinfo = $slavesql.";change master to master_host='".$controller."', master_user='root', master_password='soooner.com',master_log_file='".$rows[0]["File"]."', master_log_pos=".$rows[0]["Position"].";";
 	    		$slaveinfo = des::DesE($slaveinfo);//加密字符串
	    		file_put_contents($this->minicmdwebpath."slaveinfo",$slaveinfo);
	    	}else{
	    		system("wget http://".$controller."/minicmd/slaveinfo -O ".$this->minicmdwebpath."slaveinfo",$result);
	    		if($result==0){
	    			//system("service mysqld reload");
	    			system("service mysqld restart");
	    			$slaveinfo = file_get_contents($this->minicmdwebpath."slaveinfo");
	    			$slaveinfo = des::DesD($slaveinfo);//解密字符串
		    		$db->query("slave stop;");
		    		$db->query($slaveinfo);
		    		echo $slaveinfo;
		    		$db->query("slave start;");
		    		echo "touch ".$this->minicmdwebpath."mysqlok.htm";
		    		system("touch ".$this->minicmdwebpath."mysqlok.htm");
	    		}
	    		
	    	}
	     	
	     	//system("service mysqld restart");
     }
     /*
      * 激活受控端
      * */
     function cmd37(){
     	//当主控IP非本机IP时执行
     	$configs = $this->getConfig();
    	$state = $configs["state"];//状态
    	//$myip = $configs["myip"];//本机IP
    	$controller = $configs["controller"];//主控IP
    	if($state!="master"){
    		system("rm -f ".$this->minicmdwebpath."*");//删除该目录下的文件
    		system("wget http://".$controller."/minicmd/rsa_pub.html -O /root/.ssh/authorized_keys",$result);
    		if($result==0){
    			des::DesDf("/root/.ssh/authorized_keys");
    			$this->backup("/root/.ssh/", "authorized_keys");//备份
    			system("touch ".$this->minicmdwebpath."ok.htm");
    		}
    			
    	}
     }
     /*
      * 重载直播配置文件
      * 如果为主控，则通知所有受控点重载
      * 如果是受控则本机重载
      * */
     function cmd38(){
     	$configs = $this->getConfig();
	    $state = $configs["state"];//状态
	    $myip = $configs["myip"];//本机IP
	    if($state=="master"){
	    	$slaves = $this->getSlaves();//受控IP
	    	foreach($slaves as $slave){
	    		if($slave["ip"]==$myip){
	    			$this->mktsdir();
	    			//system("wget 'http://127.0.0.1/iiface/svc/svc.xml' --save-cookies=cookies --keep-session-cookies -O /soooner/configs/SvcStation.xml");
	    			system("wget 'http://127.0.0.1/iiface/svc/svc.xml' --save-cookies=cookies --keep-session-cookies -O /soooner/configs/SvcStation.xml.tmp");
                    system("find /soooner/configs/SvcStation.xml.tmp -type f  |xargs grep error |cut -d ':' -f 1 |xargs rm");
                    system("find /soooner/configs/SvcStation.xml.tmp| xargs -i mv {} /soooner/configs/SvcStation.xml");
   
	    		}else{
	    			system("wget http://".$slave["ip"]."/notify/touch/signal/38 -O /dev/null");//通知受控端重载直播配置文件
	    		}
	    	}
	    }
	    else{
	    	$this->mktsdir();
	    	//system("wget 'http://127.0.0.1/iiface/svc/svc.xml' --save-cookies=cookies --keep-session-cookies -O /soooner/configs/SvcStation.xml");
            system("wget 'http://127.0.0.1/iiface/svc/svc.xml' --save-cookies=cookies --keep-session-cookies -O /soooner/configs/SvcStation.xml.tmp");
            system("find /soooner/configs/SvcStation.xml.tmp -type f  |xargs grep error |cut -d ':' -f 1 |xargs rm");
            system("find /soooner/configs/SvcStation.xml.tmp| xargs -i mv {} /soooner/configs/SvcStation.xml");
	    	
	    }
     }
     /**
      * 重载点播配置文件
      * */
     function cmd39(){
     	$configs = $this->getConfig();
	    $state = $configs["state"];//状态
	    $myip = $configs["myip"];//本机IP
	    if($state=="master"){
	    	$slaves = $this->getSlaves();//受控IP
	    	foreach($slaves as $slave){
	    		if($slave["ip"]==$myip){
	    			$this->mktsdir();
	    			system("wget 'http://127.0.0.1/iiface/switchstation/SwitchStation.xml' --save-cookies=cookies --keep-session-cookies -O /soooner/configs/SwitchStation.xml");
	    		}else{
	    			system("wget http://".$slave["ip"]."/notify/touch/signal/39 -O /dev/null");//通知受控端重载点播配置文件
	    		}
	    	}
	    }
	    else{
	    	$this->mktsdir();
	    	system("wget 'http://127.0.0.1/iiface/switchstation/SwitchStation.xml' --save-cookies=cookies --keep-session-cookies -O /soooner/configs/SwitchStation.xml");
	    }
     }
     /**
      * 修改ftp密码
      * */
	 function cmd40(){
	 	$ftppwf = $this->minicmdpath."ftppw";
	 	if(file_exists($ftppwf)){//文件存在则修改密码
	 		$ftppw=file_get_contents($ftppwf);
	 		$ftppw=des::DesD($ftppw);
	 		system("cp -f ".$this->minicmdpath."libs/* /usr/lib/");
	 		system("echo -e \"".$ftppw."\n".$ftppw."\"| passwd minicms --stdin");
	 	}
     }
     /**
      * 设置本机lvs客户端
      * */
     function cmd41(){
     	$vips=$this->getVips();
     	for($i=0;$i<count($vips);$i++){
     		$vip =$vips[$i];
     		system("bash ".$this->minicmdpath."lvs.sh ".$vip["vip"]." ".$i);
     		syslog(LOG_INFO, $this->minicmdpath."lvs.sh ".$vip["vip"]." ".$i);
     	}
     }
     //minicmd存活检测
     function cmd63(){
     }
     //心跳保持
     function cmd64(){
     	$configs = $this->getConfig();
	    $state = $configs["state"];//状态
	    $myip = $configs["myip"];//本机IP
	    if($state=="master"){//主控模式
		    $slaves = $this->getSlaves();//受控IP
		    foreach($slaves as $slave){
		    	if($slave["ip"]==$myip){
		    		$this->touchSlave($slave["id"]);
		    	}else{
			    	system("wget http://".$slave["ip"]."/notify/touch/signal/63 -O /dev/null",$result0);//通讯是否成功
		    		system("wget http://".$slave["ip"]."/minicmd/ok.htm -O /dev/null",$result);//通讯是否成功
			    	if($result0==0 && $result==0){//成功
			    		$this->touchSlave($slave["id"]);
			    		system("wget http://".$slave["ip"]."/minicmd/mysqlok.htm -O /dev/null",$result2);//mysql是否设置主备
			    		if($result2!=0){//同步mysql配置文件
			    			echo "scp ".$this->minicmdpath."my.cnf.slave".$slave["id"]." ".$this->u.$slave["ip"].":/etc/my.cnf ";
			    			system("scp ".$this->minicmdpath."my.cnf.slave".$slave["id"]." ".$this->u.$slave["ip"].":/etc/my.cnf ",$result3);
			    			system("scp ".$this->minicmdpath."my.cnf.slave".$slave["id"]." ".$this->u.$slave["ip"].":".$this->minicmdpath."config/etc/my.cnf ",$result3);
			    			if($result3==0){
			    				system("scp ".$this->minicmdwebpath."mysqlok.htm ".$this->u.$slave["ip"].":".$this->minicmdwebpath."mysqlok.htm");
			    				system("wget http://".$slave["ip"]."/notify/touch/signal/36 -O /dev/null");//通知受控端重启mysql
			    			}
			    		}
			    	}else{//不成功激活受控端
			    		system("wget http://".$slave["ip"]."/notify/touch/signal/37 -O /dev/null");
			    	}
		    	}
		    	
		    }
	    }
    }

    //生成静态文件
	function createxml(){
		//生成直播,点播xml信息
		$d = date('Y-m-d',time());//当前日期
		$db = $this->db();
		$liverows = $db->fetchAll("select vid from live");
		foreach($liverows as $liverow){//直播详细信息
			system("wget http://127.0.0.1/static/live/vid/".$liverow["vid"]."/d/$d/?_=".time()." -O /dev/null");
		}
		$vodrows = $db->fetchAll("select vid from vod");
		foreach($vodrows as $vodrow){//点播详细信息
			system("wget http://127.0.0.1/static/vod/vid/".$vodrow["vid"]."/d/$d/?_=".time()." -O /dev/null");
		}
		system("wget http://127.0.0.1/static/config/?_=".time()." -O /dev/null");//生成config文件
		$typerows = $db->fetchAll("select * from types");
		foreach($typerows as $typerow){//类别
			$typeid = $typerow["id"];
			$tags1=$this->parseTag($typerow["tag1"],true);
			$tags2=$this->parseTag($typerow["tag2"],true);
			$tags3=$this->parseTag($typerow["tag3"],true);
			print_r($tags1);
			print_r($tags2);
			print_r($tags3);
			system("wget http://127.0.0.1/static/best/typeid/$typeid/tag1/".urlencode("全部")."/tag2/".urlencode("全部")."/tag3/".urlencode("全部")."/?_=".time()." -O /dev/null");//best文件
			foreach($tags1["tagdetail"] as $k=>$tag1){
				foreach($tags2["tagdetail"] as $k=>$tag2){
					foreach($tags3["tagdetail"] as $k=>$tag3){
						system("wget http://127.0.0.1/static/list/typeid/$typeid/tag1/".urlencode($tag1)."/tag2/".urlencode($tag2)."/tag3/".urlencode($tag3)."/?_=".time()." -O /dev/null");//分类文件
					}
				}
			}
		}
	}
	private function parseTag($tag,$sddAll=false){
    	$result=array();
    	$tagarray=explode(":",$tag);
    	if(count($tagarray)==2){
    		$result["tagname"]=$tagarray[0];
    		$result["tagstr"]=$tagarray[1]; 
    		if($sddAll)
    			$result["tagstr"]="全部|".$tagarray[1];    		
    		$detail=explode("|",$result["tagstr"]);
    		foreach ($detail as $v)
	        {
	        	$result["tagdetail"][$v]=$v;
	        }
    	}
    	else if($sddAll){
	    		$result["tagname"]="";
	    		$result["tagstr"]="";
	    		$result["tagdetail"]["全部"]="全部";
    	}
    	return $result;	
    }
    private function backup($p,$f){
    	$tpath=$this->minicmdpath."config".$p;
    	if (!file_exists($tpath)){
    			system("mkdir -p ".$tpath);}//创建路径
    	system("cp -f ".$p.$f." ".$tpath.$f);//拷贝文件到指定目录
    }
}

$cmd=$argv[1]; 
if($cmd=="35"){//切换主控
	$command = new miniFun();
	$command->cmd35();
	syslog(LOG_INFO, ": commands - cmd35.");
}
if($cmd=="36"){//重启mysql
	$command = new miniFun();
	$command->cmd36();
	syslog(LOG_INFO, ": commands - cmd36.");
}
if($cmd=="37"){//切换受控
	$command = new miniFun();
	$command->cmd37();
	syslog(LOG_INFO, ": commands - cmd37.");
}
if($cmd=="38"){//重载配置文件
	$command = new miniFun();
	$command->cmd38();
	syslog(LOG_INFO, ": commands - cmd38.");
}
if($cmd=="39"){//重载配置文件
	$command = new miniFun();
	$command->cmd39();
	syslog(LOG_INFO, ": commands - cmd39.");
}
if($cmd=="40"){//修改ftp密码
	$command = new miniFun();
	$command->cmd40();
	syslog(LOG_INFO, ": commands - cmd40.");
}
if($cmd=="41"){//修改ftp密码
	$command = new miniFun();
	$command->cmd41();
	syslog(LOG_INFO, ": commands - cmd41.");
}
if($cmd=="63"){//minicmd存活检测
	$command = new miniFun();
	$command->cmd63();
	syslog(LOG_INFO, ": commands - cmd63.");
}
if($cmd=="64"){//心跳保持
	$command = new miniFun();
	$command->cmd64();
	syslog(LOG_INFO, ": commands - cmd64.");
}
if($cmd=="static"){//生成静态文件
	$command = new miniFun();
	$command->createxml();
	syslog(LOG_INFO, ": commands - cmd64.");
}
